package com.example.demo02.controller.FilesUpload;



import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Tag(name = "多文件上传接口")
@RestController
public class FilesUploadController {
    @PostMapping("/uploads")
    public String uploads(@RequestParam("uploadFiles")MultipartFile[] uploadFiles, HttpServletRequest request) {
        if (uploadFiles == null || uploadFiles.length == 0) {
            return "空文件";
        }
        // 获取上传目标文件夹的绝对路径（也能是本地路径）
        String realPath = "D:/IDEA/code/java/demo02/MyFile";
//        String realPath = request.getServletContext().getRealPath("/uploadFile");
        // 创建为File 对象（目录）
        File parentDir = new File(realPath);
        // 如果不存在这个目录则自动创建目录
        if (!parentDir.isDirectory()) {
            parentDir.mkdir();
        }
        // 循环上传
        for (MultipartFile uploadFile:uploadFiles) {
            String filename = uploadFile.getOriginalFilename();
            File target = new File(parentDir, filename); // 创建上传目标文件
            try {
                uploadFile.transferTo(target); // 源文件拷贝到目标文件
                System.out.println(target.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        System.out.println(formatter.format(date));
        return "当前时间" + formatter.format(date) + "多个文件上传成功";
    }

}
